/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package giuliani_mapelli_marocco.business;
import giuliani_mapelli_marocco.entity.Event;
import giuliani_mapelli_marocco.entity.User;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

@Stateless
public class ImportExportManager {
    
    @PersistenceContext
    private EntityManager em;
    @EJB
    private EventManager evm;
    @EJB
    private UserManager um;

    /**
     * This method will import the calendar from an well formed xml file thanks to the JAXB function, 
     * if are present time inconsistency
     * the import is not performed.
     * @param inStr the strem file used for the import
     * @return false if it's impossible to import the calendar, true otherwise
     */ 
    public boolean importCalendar(InputStream inStr) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(Events.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Events events = (Events) unmarshaller.unmarshal(inStr);
         
        for (Event e : events.getEvents()) {
             //set the organizer of the event the logged user
            e.setOrganizer(um.getLoggedUser());
            String consistencyResult = evm.checkEventConsistency(e, um.getLoggedUser().getUsername());
            if(!consistencyResult.equals("")) {
                return false;
            }
        }
        for (Event e : events.getEvents()) {
            e.setId(null);
            e.setOrganizer(um.getLoggedUser());
            ArrayList<User> participantsList= new ArrayList();
            participantsList.add(um.getLoggedUser());
            e.setUserCollection1(participantsList);
            e.setUserCollection(new ArrayList());
            evm.save(e);
        }
        return true;
    }
		
    /**
     * This method will export the calendar in a xml file using JAXB function in a path selected by the user
     * @return the xml file created
     * @throws JAXBException 
     */
    public ByteArrayOutputStream exportCalendar() throws JAXBException {
        
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        JAXBContext context = JAXBContext.newInstance(Events.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
       
        Events events = new Events();
        List<Event> eventUser = em.createQuery("SELECT e FROM Event e WHERE (e.organizer =:organizer AND e.deleted =:deleted)")
                .setParameter("organizer", um.getLoggedUser()).setParameter("deleted", false).getResultList();
        events.setEvents(eventUser); //Set all the DB events of the user
        // Write to OutputStream
        m.marshal(events, out);
        return out;
    }
    
    //Handler class to export/import the calendar
    @XmlRootElement(name = "calendar")
      static class Events {
        
        List<Event> events = new ArrayList<Event>();
        
        public Events() {   
        }

         public List<Event> getEvents() {
            return this.events;
        }

         public void setEvents(List<Event> events) {
            this.events = events;
        }
    } 
}
   

